import {createClientDB} from './common'
import mongoose from 'mongoose';
/**
 * 为什么下面的model要这么写
 * 因为在开发环境中编写代码的时候文件会多次执行
 * 连接数据库也会多次 model生成也是多次 会报错。
 * 存为全局变量只 生成一次
 */
if(!global._numindex){
    global._numindex = 1;
}
global._numindex ++;
let is_database_success = false;
if (process.env.NODE_ENV !== "production"){
    if(!global._createClientDB){
        createClientDB((connect)=>{
            global._createClientDB = connect
            is_database_success = true;//数据库连接成功
        },(err)=>{
            is_database_success = false;//数据库连接成功
            console.log('shun11',err)
        })
    }
}else{
    createClientDB((connect)=>{
        is_database_success = true;//数据库连接成功
    },(err)=>{
        is_database_success = false;//数据库连接失败
        console.log('shun12',err)
    })
}

const UserSchema = new mongoose.Schema({
    account:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    },
    nickname:{
        type:String,
        required:true
    },
});
const get_user = ()=>{
    let User;
    if(process.env.NODE_ENV === 'development'){
        if(!global._mongoDBmodel_user){
            User = mongoose.model('user', UserSchema);
            global._mongoDBmodel_user = User;
        }else{
            User = global._mongoDBmodel_user;
        }
    }else{
        User = mongoose.model('user', UserSchema);
    }
    return User;
}
export const User = get_user();

const ArticleSchema = new mongoose.Schema({
    account:{ //账号
        type:String,
        required:true
    },
    title:{//文章标题
        type:String,
        required:true
    },
    content:{//文章内容
        type:String,
        required:true
    },
    likenum:{
        type: String,
        required:true
    },
    nickname:{
        type: String,
        required:true
    },
    create_time:{
        type: Number,
        required:true
    }
});
const get_article = ()=>{
    let Article;
    if(process.env.NODE_ENV === 'development'){
        if(!global._mongoDBmodel_article){
            Article = mongoose.model('article', ArticleSchema);
            global._mongoDBmodel_article = Article;
        }else{
            Article = global._mongoDBmodel_article;
        }
    }else{
        Article = mongoose.model('article', ArticleSchema);
    }
    return Article;
}
export const Article = get_article();